package com.example.stlink.utils.activityUtil;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.example.stlink.activitys.LoginActivity;
import com.example.stlink.R;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.request.UserRegisterRequest;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.utils.CommonUtils;
import com.example.stlink.utils.httpUtils.PostBodyParamHttpUtils;
import com.google.android.material.textfield.TextInputLayout;

/**
 * 注册相关方法
 */
public class RegisterUtil {

    private static RegisterUtil registerUtils = new RegisterUtil();

    private static AppCompatActivity registerActivity;
    private static String userName;
    private static String pwdFirst;
    private static String pwdSecond;
    private static String pwd;
    private static TextInputLayout rlPwdFirst;
    private static TextInputLayout rlPwdSecond;
    private static TextInputLayout tlId;

    private static Handler handler;

    /**
     * 为注册按钮添加点击监听事件
     * @param appCompatActivity 上下文
     * @param btRegister 注册按钮
     * @param etId 昵称输入
     * @param etPwdFirst 第一次密码输入框
     * @param etPwdSecond 第二次密码输入框
     */
    public static void userRegister(AppCompatActivity appCompatActivity,
                                    Button btRegister, EditText etId,
                                    EditText etPwdFirst, EditText etPwdSecond){
        registerActivity = appCompatActivity;
        btRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                userName = etId.getText().toString();
                pwdFirst = etPwdFirst.getText().toString();
                pwdSecond = etPwdSecond.getText().toString();

                tlId = appCompatActivity.findViewById(R.id.rl_id);
                rlPwdFirst = appCompatActivity.findViewById(R.id.rl_pwd_first);
                rlPwdSecond = appCompatActivity.findViewById(R.id.rl_pwd_second);

                //用户名不能为空
                if( !TextUtils.isEmpty(userName) ){
                    tlId.setError("");
                    //密码不能为空
                    if( !TextUtils.isEmpty(pwdFirst)){
                        rlPwdFirst.setError("");
                        if( !CommonUtils.isSamePwd(pwdFirst, pwdSecond)){
                            rlPwdSecond.setError("两次输入不相同");
                        }else{
                            rlPwdSecond.setError("");
                            pwd = CommonUtils.encryptAndDencrypt(pwdFirst);
                            registerUtils.registerRequest();

                            handler = new Handler(Looper.getMainLooper()){
                                @Override
                                public void handleMessage(@NonNull Message msg) {
                                    super.handleMessage(msg);
                                    tlId.setError(msg.obj.toString());
                                }
                            };
                        }
                    }else{
                        rlPwdFirst.setError("密码不能为空");
                    }
                }else{
                    tlId.setError("用户名不能为空");
                }
            }
        });
    }

    /**
     * 向服务器请求数据的时候先
     */
    private void registerRequest(){

        new Thread(() -> {
            UserRegisterRequest requestObj = new UserRegisterRequest();
            //fastJson将对象转换为JSON字符串
            requestObj.setUserName(userName);
            //即将云端发送的密码要经过MD5加密，也就是异或运算和MD5的双重加密
            requestObj.setPassword(CommonUtils.MD5(pwd));
            requestObj.setRoleId( (Integer) registerActivity.getIntent().getExtras().get(ModelFieldConstants.ROLE_ID));
            System.out.println( "requestObj : " + requestObj + "..............................");
            String json = JSON.toJSONString(requestObj);
            String url = UrlConstants.USER_REGISTER;

            new PostBodyParamHttpUtils() {
                @Override
                public void nextMethod(BaseResponse<Object> baseResponse) {
                    //保存在本地的密码只是进行了简单的异或运算
                    CommonUtils.localSave(registerActivity, userName, pwdFirst, true);
                    Intent intent = new Intent(registerActivity, LoginActivity.class);
                    //将bundle中的数据再次传入新的intent中
                    intent.putExtras(registerActivity.getIntent().getExtras());
                    registerActivity.startActivity(intent);
                }
                @Override
                public void failedMethod(BaseResponse<Object> baseResponse) {
                    Message message = new Message();
                    message.obj = baseResponse.getMsg();
                    handler .sendMessage(message);
                }
            }.postConnect(url, json);
        }).start();
    }
}
